//
//  MessageViewViewController.m
//  Message
//
//  Created by Fanty on 13-12-17.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "MessageViewController.h"
#import <ChamleonSDK/CApplication.h>
#import "MessageModule.h"
#import "MessageRecordHeaderView.h"
#import "MessageRecordCell.h"
#import "MessageModel.h"

@interface MessageViewController ()<UITableViewDataSource,UITableViewDelegate,MessageRecordHeaderViewDelegate>
-(void)initNavigation;
-(void)backClick;
-(void)reloadGroupArray;
-(void)reloadMessageArray;

-(void)rightNavClick;
-(void)createRrightNavItem;

- (UIImage *)imageTransform:(UIImage *)image rotation:(UIImageOrientation)orientation;

-(void)cube_MessageUpdated;

@end

@implementation MessageViewController

- (id)init{
    self = [super init];
    if (self) {
        
        groupArray=[[NSMutableArray alloc] initWithCapacity:2];
        messageArray=[[NSMutableArray alloc] initWithCapacity:2];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cube_MessageUpdated) name:@"Cube_MessageUpdated" object:nil];
        self.title = @"消息推送";
        
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    selectedModuleIdentifier=nil;
    [self reloadGroupArray];

    
    self.view.backgroundColor=[UIColor whiteColor];

    [self initNavigation];
    
    CGRect rect=self.view.bounds;
    rect.origin.y=CGRectGetMaxY(navigationBar.frame);
    rect.size.height-=rect.origin.y;
    
    
    tableView=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    tableView.backgroundColor=[UIColor whiteColor];
    tableView.delegate=self;
    tableView.dataSource=self;

    UIView* v=[[UIView alloc] init];
    v.backgroundColor=[UIColor clearColor];
    tableView.tableFooterView=v;
    tableView.tableHeaderView=v;

    
    [self.view addSubview:tableView];
    
    [self createRrightNavItem];

}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark method

-(void)initNavigation{
    navigationBar=[[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 20.0f, self.view.frame.size.width, 44.0f)];
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0){
        navigationBar.barTintColor = [UIColor colorWithRed:70/255.0 green:135/255.0 blue:199/255.0 alpha:1];
        navigationBar.translucent = NO;
        UIColor * cc = [UIColor whiteColor];
        NSDictionary * dict = [NSDictionary dictionaryWithObject:cc forKey:UITextAttributeTextColor];
        navigationBar.titleTextAttributes = dict;
    }
    else{
        [navigationBar setTintColor: [UIColor colorWithRed:70/255.0 green:135/255.0 blue:199/255.0 alpha:1]];
    }
    navigationItem=[[UINavigationItem alloc] initWithTitle:self.title];
    navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(backClick)];
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0f)
        [navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    [navigationBar pushNavigationItem:navigationItem animated:NO];
    [self.view addSubview:navigationBar];

}

-(void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)rightNavClick{
    [tableView setEditing:!tableView.editing animated:YES];
    [self createRrightNavItem];
}

-(void)createRrightNavItem{
    if([groupArray count]<1){
        navigationItem.rightBarButtonItem=nil;
        return;
    }
    navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:(tableView.editing?@"取消":@"编辑") style:UIBarButtonItemStyleDone target:self action:@selector(rightNavClick)];
    
    if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0f)
        [navigationItem.rightBarButtonItem setTintColor:[UIColor whiteColor]];

}

- (UIImage *)imageTransform:(UIImage *)image rotation:(UIImageOrientation)orientation{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    switch (orientation) {
        case UIImageOrientationLeft:
            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationRight:
            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case UIImageOrientationDown:
            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = -rect.size.width;
            translateY = -rect.size.height;
            break;
        default:
            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = 0;
            translateY = 0;
            break;
    }
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newPic;
}


-(void)reloadGroupArray{
    [groupArray removeAllObjects];
    MessageModule* messageModule=(MessageModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Message"];
    NSArray* array=[messageModule.messageManager messageGroupList];
    if([array count]>0)
        [groupArray addObjectsFromArray:array];
}

-(void)reloadMessageArray{
    [messageArray removeAllObjects];
    if([selectedModuleIdentifier length]>0){
        MessageModule* messageModule=(MessageModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Message"];
        NSArray* array=[messageModule.messageManager messageList:selectedModuleIdentifier];
        [messageArray addObjectsFromArray:array];
    }
}

-(void)cube_MessageUpdated{
    [self reloadGroupArray];
    [self reloadMessageArray];
    [tableView reloadData];
    
    [self createRrightNavItem];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)__tableView{
    return [groupArray count];
}

- (NSInteger)tableView:(UITableView *)__tableView numberOfRowsInSection:(NSInteger)section{
    MessageGroupModel* groupModel=[groupArray objectAtIndex:section];
    if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier])
        return [messageArray count];
    else
        return 0.0f;
}

- (UITableViewCell *)tableView:(UITableView *)__tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageRecordCell *cell = [__tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[MessageRecordCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    MessageModel* messageModel=[messageArray objectAtIndex:[indexPath row]];
    
    [cell title:messageModel.title content:messageModel.content time:messageModel.receiveTime isRead:messageModel.isRead];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)__tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MessageModel* messageModel=[messageArray objectAtIndex:[indexPath row]];
    
    return [MessageRecordCell cellHeight:messageModel.title content:messageModel.content width:__tableView.frame.size.width];
    
}

- (UIView *)tableView:(UITableView *)__tableView viewForHeaderInSection:(NSInteger)section{
    
    MessageGroupModel* groupModel=[groupArray objectAtIndex:section];
    
    MessageRecordHeaderView *headerView = [[MessageRecordHeaderView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 36)];
    headerView.delegate = self;
    headerView.section = section;
    headerView.moduleId = groupModel.moduleIdentifer;
    
    
    [headerView configureWithIconUrl:nil moduleName:groupModel.moduleName messageCount:[NSString stringWithFormat:@"%d",groupModel.totalCount] sectionIndenx:section withUnReadCount:[NSString stringWithFormat:@"%d",groupModel.unReadCount]];
    
    headerView.tag = section + 10;
    
    
    UIImageView* arrowImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Message.bundle/images/xmpp_arrow.png"]];
    arrowImageView.frame= CGRectMake(17, 15, 10, 11);
    if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
        arrowImageView.image  = [self imageTransform:arrowImageView.image rotation:UIImageOrientationRight];
    }
    [headerView addSubview:arrowImageView];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 36;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)__tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(__tableView.editing)
        return UITableViewCellEditingStyleDelete;
    return UITableViewCellEditingStyleNone;
}


//修改删除按钮的文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}


- (void)tableView:(UITableView *)__tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        MessageModule* messageModule=(MessageModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Message"];
        MessageModel* messageModel=[messageArray objectAtIndex:[indexPath row]];
        [messageModule.messageManager removeMesageById:messageModel.messageId];
        [messageArray removeObject:messageModel];

        [__tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        
        if([messageArray count]<1 && [selectedModuleIdentifier length]>0){
            __block int newSelected=-1;
            [groupArray enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL* stop){
                MessageGroupModel* groupModel=obj;
                if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
                    newSelected=index;
                    *stop=YES;
                }
                
            }];
            
            selectedModuleIdentifier=nil;
            if(newSelected>-1){
                [groupArray removeObjectAtIndex:newSelected];
                [tableView deleteSections:[NSIndexSet indexSetWithIndex:newSelected] withRowAnimation:UITableViewRowAnimationAutomatic];
                
                if([groupArray count]<1)
                    [self createRrightNavItem];
            }
        }
    }
}

- (void)tableView:(UITableView *)__tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageModel* messageModel=[messageArray objectAtIndex:[indexPath row]];
    messageModel.isRead=YES;
    MessageModule* messageModule=(MessageModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Message"];
    [messageModule.messageManager setIsReadMessageById:messageModel.messageId];
    [__tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    [__tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark messagerecordheaderview delegate

-(void)shouldShowCellInModule:(NSString *)moduleId atIndex:(NSInteger)section{
    
    MessageGroupModel* groupModel=[groupArray objectAtIndex:section];
    moduleId=groupModel.moduleIdentifer;
    __block int oldSelected=-1;
    __block int newSelected=-1;

    if([moduleId isEqualToString:selectedModuleIdentifier]){
        selectedModuleIdentifier=nil;
        [groupArray enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL* stop){
            MessageGroupModel* groupModel=obj;
            if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
                oldSelected=index;
            }
            else if([groupModel.moduleIdentifer isEqualToString:moduleId]){
                newSelected=index;
            }
        }];
    }
    else{
        [groupArray enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL* stop){
            MessageGroupModel* groupModel=obj;
            if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
                oldSelected=index;
            }
            else if([groupModel.moduleIdentifer isEqualToString:moduleId]){
                newSelected=index;
            }
        }];
        selectedModuleIdentifier=moduleId;
    }
    
    
    [self reloadMessageArray];
    
    

    [tableView reloadData];
}


-(void)deleteModuleData:(NSInteger)section{
    MessageModule* messageModule=(MessageModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Message"];
    
    MessageGroupModel* groupModel=[groupArray objectAtIndex:section];
    [messageModule.messageManager removeMessageByGroup:groupModel.moduleIdentifer];
    
    if([groupModel.moduleIdentifer isEqualToString:selectedModuleIdentifier]){
        [groupArray removeObjectAtIndex:section];
        selectedModuleIdentifier=nil;
        [tableView deleteSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else{
        [groupArray removeObjectAtIndex:section];
    }
    if([groupArray count]<1)
        [self createRrightNavItem];
}




@end
